package com.why.simpleboot.core.server.netty.response;


import com.why.simpleboot.core.server.netty.serialize.JacksonSerializer;
import com.why.simpleboot.core.server.netty.serialize.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.*;

import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;

/**
 * @program: why-simpleboot
 * @description:
 * @author: @why
 * @create: 2021-05-14 16:59
 **/
public class SimpleResponse {

    private static final Serializer SERIALIZER = new JacksonSerializer();

    /**
     * 将传递进来的对象序列化，并封装成Response
     *
     * @param o
     * @return
     */
    public static FullHttpResponse createOk(Object o) {
        byte[] bytes = null;
        if (o == null) {
            bytes = "成功收到响应~".getBytes();
        } else {
            bytes = SERIALIZER.serialize(o);
        }

//        将一个字节数组包装成ByteBuf
        ByteBuf buffer = Unpooled.wrappedBuffer(bytes);
        FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer);
        fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
        fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, fullHttpResponse.content().readableBytes());
        return fullHttpResponse;
    }

    /**
     * 错误处理
     *
     * @param path
     * @return
     */
    public static FullHttpResponse createError(String path, String reason, HttpResponseStatus status) {
        ErrorResponse errorResponse = new ErrorResponse(INTERNAL_SERVER_ERROR.code(),
                "{" + reason + "}", "{" + path + "}");
        byte[] bytes = SERIALIZER.serialize(errorResponse);
        FullHttpResponse fullHttpResponse = null;
//        将一个字节数组包装成ByteBuf
        ByteBuf buffer = Unpooled.wrappedBuffer(bytes);
        fullHttpResponse = new
                DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, buffer);
        fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
        fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, fullHttpResponse.content().readableBytes());

        return fullHttpResponse;

    }

}
